package com.example.blog_system_ssm.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.example.blog_system_ssm.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RefreshTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session= request.getSession(false);
        //设置ip信息用于统计阅读量
        if(session==null){
            session= request.getSession();
            session.setAttribute(Constant.SESSION_USERIP_KEY,request.getRemoteAddr());
        }else{
            session.setAttribute(Constant.SESSION_USERIP_KEY,request.getRemoteAddr());
        }

        String token=request.getHeader("authorization");
        String key=Constant.LOGIN_USER_KEY+token;

        if(StrUtil.isBlank(token)){
            return true;
        }
        //基于token从redis获取用户信息
        Map<Object,Object> userMap=redisTemplate.opsForHash().entries(key);
        //用户不存在
        if(MapUtil.isEmpty(userMap)){
            return true;
        }
        //将hash对象转化为user对象
        UserInfo userInfo= BeanUtil.fillBeanWithMap(userMap,new UserInfo(),false);
        //每次请求将用户保存到ThreadLocal
        UserThreadLocal.put(userInfo);
        //刷新token有效期
        redisTemplate.expire(key,30, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求完成后清除用户信息，防止内存泄露
        UserThreadLocal.remove();
    }
}
